import 'dart:io';

import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module/module_create_wallet/pages/create_mnemonic_page.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/widgets/dapp_title.dart';
import 'package:aichat_flutter_wallet/module/module_wallet/pages/wallet_add_token.dart';
import 'package:aichat_flutter_wallet/module/module_wallet/pages/wallet_mpc_securitymanager.dart';
import 'package:aichat_flutter_wallet/module/module_wallet/pages/wallet_set_node.dart';
import 'package:aichat_flutter_wallet/module/module_wallet/widgets/assets_network_comp.dart';
import 'package:aichat_flutter_wallet/module/module_wallet/widgets/assets_network_widget.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/refresh/assets_pull_refresh_custom_header.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_util/lib_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/provider/token_list_provider.dart';
import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/router/Routers.dart';
import '../../../module_common/router/app_route_page_utils.dart';
import '../../../module_common/utils/auth.dart';
import '../../../module_common/widgets/header/page_wallet_header.dart';
import '../../../module_common/widgets/token_widget/token_list_page.dart';
import '../../module_wallet_manage/pages/wallet_personal_center_page.dart';
import '../widgets/assets_card_comp.dart';
import '../widgets/assets_chain_comp.dart';
import 'package:aichat_flutter_wallet/module_common/mpc_help/mpcManager.dart';

import '../widgets/sheet/confirm_alert.dart';
class WalletAssetsPage extends StatefulWidget {
  const WalletAssetsPage({super.key});

  @override
  State<WalletAssetsPage> createState() => _WalletIndexPageState();
}

class _WalletIndexPageState extends State<WalletAssetsPage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: [
          Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: PublicImage(
                image: 'assets/images/create_wallet/wallet_bg.png',
                width: double.infinity,
                height: 300.h,
              )),
          WalletAssetsPageContainer()
        ],
      ),
      color: Colors.white,
    );
  }
}

class WalletAssetsPageContainer extends StatefulWidget {
  const WalletAssetsPageContainer({super.key});

  @override
  State<WalletAssetsPageContainer> createState() =>
      _WalletIndexPageContainerState();
}

class _WalletIndexPageContainerState extends State<WalletAssetsPageContainer>
    with RouteAware {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() {
    context
        .read<TokenListNotifier>()
        .refreshTokenListFromServer()
        .then((value) {
      _refreshController.refreshCompleted();
    }).catchError((_) {
      _refreshController.refreshCompleted();
    });
  }

  @override
  void initState() {
    super.initState();
    checkUserMPCVersion();
    // 判断该用户 是否 持有 地址
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _requestTokenList();
    });
  }

  // 检测用户 版本是否为 1
  void checkUserMPCVersion(){
    try{
      final walletInfo= Provider.of<WalletInfoNotifier>(context, listen: false).walletInfo;
      if(walletInfo!=null){
        //  强制用户走 重铸流程
        //  判断分片 是否是 version 1 是的话 重新 重铸流程
        final privateKey = walletInfo.privateKey;
        // final privateKey = '';
        kaiPrint('privateKey ${privateKey.length}');
        kaiPrint('privateKey ${privateKey}');
        mpcTool().getVersionFromFrag(privateKey).then((value){
          kaiPrint('current mpc privateKey version $value');
          if(value==1){
            showDialog(
              context: context,
              builder: (context) {
                return MyDialog(
                  title: 'Important-Note',
                  detail:
                  'Currently, the wallet\'s MPC does not support tron and Solana chains. If you want current MPC support, recast the MPC.',
                  confirmText: 'Upgrade now',
                  cancelText: 'Not upgrading yet',
                  onConfirm: () {
                    Navigator.of(context).pop();
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => WalletMPCSecurityManager(
                            pageType: MPCManagerPageType.Recast,
                            version: 1, // 此版本号 决定 是否 升级 钱包的操作
                          )),
                    );
                  },
                  onCancel: () {
                    Navigator.of(context).pop();
                  },
                );
              },
            );
          }
        });
      }
    }catch(e){
      kaiPrint('checkUserMPCVersion $e');
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    /// 路由订阅
    AppRouterPageUtils().routeObserver.subscribe(this, ModalRoute.of(context)!);
  }

  @override
  void dispose() {
    /// 取消路由订阅
    AppRouterPageUtils().routeObserver.unsubscribe(this);
    _refreshController.dispose();
    super.dispose();
  }

  @override
  void didPopNext() {
    super.didPopNext();
    //其他页面返回到当前页面
    if (ModalRoute.of(context)!.isCurrent) {
      _requestTokenList();
      // checkUserMPCVersion();
    }
  }
  _requestTokenList() {
    return context.read<TokenListNotifier>().refreshTokenListFromServer();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PageWalletHeaderCom(
        title: 'Wallet',
        height: 98.w,
        definedGoBack: true,
        goBack: () {
          //  关闭页面
          NativeChannelBridge.instance.closeFlutterPage(num: 1);
        },
        WidgetLeft: AssetsNetworkComp(),
        WidgetRight: Container(
          height: double.infinity,
          padding: EdgeInsets.only(right: 20.w, bottom: 5.w, top: 0),
          alignment: Alignment.bottomLeft,
          child: Row(
            children: [
              AssetsNetworkWidget(
                onClick: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => WalletSetNode(chain: null),
                        settings: RouteSettings(name: Routes.walletSetNode)),
                  );
                },
              ),
              AssetsChainComp()
            ],
          ),
        ),
        goWalletCenter: () {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => WalletPersonalCenterPage(),
                  settings: RouteSettings(name: Routes.walletPersonal)));
        },
      ),
      backgroundColor: Colors.transparent,
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: false,
        header: AssetsPullRefreshCustomHeader(),
        controller: _refreshController,
        onRefresh: _onRefresh,
        child: Column(
          children: [
            SizedBox(
              height: 16.w,
            ),
            AssetsCardComp(),
            DAppTitle(
                title: 'Tokens',
                rightDom: InkWell(
                  child: PublicImage(
                    image: 'assets/images/wallet/token_add.png',
                    width: 20.w,
                    height: 20.w,
                  ),
                  onTap: () {
                    // 下拉刷新 状态禁止跳转
                    if (_refreshController.isRefresh) {
                      Toast.show(context,
                          message:
                              "The network is not fully loaded yet, please try again later.",
                          status: '0',
                          position: Dpositon.top);
                      return;
                    }
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => WalletAddToken(),
                        settings: RouteSettings(name: Routes.walletAddToken),
                      ),
                    );
                    //WalletAddToken
                    // Routes.navigateTo(
                    //   context,
                    //   Routes.walletAddToken,
                    // );
                  },
                )),
            SizedBox(
              height: 4.w,
            ),
            Expanded(child: const TokenListPage()),
            Visibility(
                visible:
                    context.watch<WalletInfoNotifier>().wallet?.needBackup() ??
                        false,
                child: Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Align(
                      alignment: Alignment.bottomCenter,
                      child: Container(
                        padding: EdgeInsets.only(
                            left: 15.w, right: 15.w, top: 15.w, bottom: 15.w),
                        margin: EdgeInsets.all(14.w),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius:
                                BorderRadius.all(Radius.circular(12.w)),
                            border: Border.all(
                                color: Color.fromRGBO(239, 239, 239, 1),
                                width: 1)),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            PublicImage(
                              image: "assets/images/status/warn.png",
                              width: 20.w,
                              height: 20.w,
                            ),
                            SizedBox(
                              width: 10.w,
                            ),
                            Expanded(
                                child: GestureDetector(
                              onTap: () async {
                                Authentication()
                                    .startLocalAuth()
                                    .then((result) {
                                  if (result) {
                                    Navigator.of(context).push(
                                      MaterialPageRoute(builder: (_) {
                                        return CreateMnemonicPage(
                                          wallet_id: context
                                              .read<WalletInfoNotifier>()
                                              .walletId,
                                        );
                                      }),
                                    );
                                  }
                                });
                              },
                              child: Text(
                                'You have not backed up your mnemonic phrase.To prevent the loss of your wallet,please back up your mnemonic phrase',
                                style: TextStyle(
                                    fontSize: 12.sp,
                                    height: 18.w / 12.w,
                                    color: Color.fromRGBO(51, 51, 51, 1)),
                              ),
                            ))
                          ],
                        ),
                      )),
                )),
            SizedBox(
              height: (Platform.isIOS ? 49.w : 0) + 20.w,
            )
            // Container(
            //   color: Colors.black,
            //   margin: EdgeInsets.only(bottom: Platform.isIOS ? 49 : 0),
            //   width: 400,
            //   height: 1,
            // )
          ],
        ),
      ),
    );
  }
}
